import { HYEventStore } from 'hy-event-store'
import { getSongDetail, getSongLyric } from '../service/api_player'
import { parseLyric } from '../utils/parse-lyric'

// const audioContext = wx.createInnerAudioContext() // 前台播放
const audioContext = wx.getBackgroundAudioManager() // 后台播放

const playerStore = new HYEventStore({
	state: {
		isFirstPlay: true,
		isStoping: false,

		id: 0,
		currentSong: {},
		duration: 0,
		lyricInfos: [],

		currentTime: 0,
		currentLyric: '',
		lyricScrollTop: 0,

		// 播放模式 (0:循环,1:单曲,2:随机)
		playModeIndex: 0,
		// 暂停/播放
		isPlaying: false,
		// 播放列表
		playSongsList: [],
		playSongIndex: 0
	},
	actions: {
		playMusicWithSongIdAction(ctx, { id, isRefresh = false }) {
			if(ctx.id == id && !isRefresh) {
				this.dispatch('changeMusicPlayStatuAction', true)
				return
			} 
			// 对上次数据进行处理
			ctx.id = id
			ctx.isPlaying = true
			ctx.currentSong = {}
			ctx.duration = 0
			ctx.lyricInfos = []
			ctx.currentTime = 0
			ctx.currentLyric = ''
			ctx.lyricScrollTop = 0

			// 请求歌曲详情
			getSongDetail(id).then(res => {
				ctx.currentSong = res.songs[0]
				ctx.duration = res.songs[0].dt
				audioContext.title = res.songs[0].name
			})
			// 请求歌词
			getSongLyric(id).then(res => {
				const lyricString = res.lrc.lyric
				const lyricInfos = parseLyric(lyricString)
				ctx.lyricInfos = lyricInfos
			})
			// 播放歌曲(先停在播)
			audioContext.stop() 
			audioContext.src = `https://music.163.com/song/media/outer/url?id=${id}.mp3`
			audioContext.title = id
			audioContext.autoplay = true

			// 监听AudioContext事件(只需要监听一次)
			if(ctx.isFirstPlay) {
				this.dispatch('setupAudioContextAction')
				ctx.isFirstPlay = false
			}
		},

		setupAudioContextAction(ctx) {
			// 监听歌曲可以播放
			audioContext.onCanplay(() => {
				audioContext.play()
			})

			// 监听时间改变
			audioContext.onTimeUpdate(() => {
				// 把秒转为毫秒
				const currentTime = audioContext.currentTime * 1000
				
				// 根据当前时间修改currentTime
				ctx.currentTime = currentTime

				// 设置歌词的索引与内容
				const lyricInfos = ctx.lyricInfos
				for(let i = 0; i < lyricInfos.length; i++){
					if(currentTime < lyricInfos[i].time) {
						if(i-1 < 0) return lyricInfos[i].text
						const currentLyric = lyricInfos[i-1].text
						if(ctx.currentLyric === currentLyric) return
						ctx.currentLyric = currentLyric
						ctx.lyricScrollTop = (i-1) * 35 
						break
					}
				}
			})

			// 监听播放完成
			audioContext.onEnded(() => {
				this.dispatch('changeNewMusicAction')
			})

			// 监听音乐播放/暂停/停止
			audioContext.onPlay(() => {
				ctx.isPlaying = true
			})
			audioContext.onPause(() => {
				ctx.isPlaying = false
			})
			// onStop之后里面的src/id/title都会被清空
			audioContext.onStop(() => {
				ctx.isPlaying = false
				ctx.isStoping = true
			})
		},

		changeMusicPlayStatuAction(ctx, isPlaying = true) {
			ctx.isPlaying = isPlaying
			console.log('是否播放~', ctx.isPlaying , ctx.isStoping);
			if(ctx.isPlaying && ctx.isStoping) {
				audioContext.src = `https://music.163.com/song/media/outer/url?id=${ctx.id}.mp3`
				audioContext.title = ctx.currentSong.name
				ctx.isStoping = false
			}
			ctx.isPlaying ? audioContext.play() : audioContext.pause()
		},
		
		changeNewMusicAction(ctx, isNext = true) {
			let index = ctx.playSongIndex
			switch (ctx.playModeIndex) { // (0:循环,1:单曲,2:随机)
				case 0:
					index = isNext? index + 1 : index - 1
					
					if(index === -1) index = ctx.playSongsList.length - 1
					if(index === ctx.playSongsList.length) index = 0
					break;
				case 1:
					break;
				case 2:
					index = Math.floor(Math.random() * ctx.playSongsList.length)
					break;
				default:
					break;
			}
			let currentSong = ctx.playSongsList[index]
			if(!currentSong) {
				currentSong = ctx.currentSong
			}else {
				// 记录最新的索引
				ctx.playSongIndex = index
			}

			this.dispatch('playMusicWithSongIdAction', { id: currentSong.id, isRefresh:true })
		}
	}
})

export {
	audioContext,
	playerStore
} 